package com.dl7.mvp.video.ui;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.baidu.mobads.AdSettings;
import com.baidu.mobads.AdView;
import com.baidu.mobads.AdViewListener;
import com.bumptech.glide.Glide;
import com.dl7.mvp.CommonConstant;
import com.dl7.mvp.video.adapter.VideoAlbumDetailAdapter;
import com.dl7.mvp.video.bean.VideoCategoryList;
import com.dl7.mvp.video.bean.VideoInfo;
import com.dl7.mvp.XApp;
import com.dl7.mvp.api.RetrofitService;
import com.dl7.mvp.base.baseadapter.BaseRecyclerViewAdapter;
import com.dl7.mvp.mvp.R;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack;
import com.shuyu.gsyvideoplayer.model.GSYVideoModel;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.ListGSYVideoPlayer;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public class VideoPlayerActivity extends RxAppCompatActivity {
    RecyclerView mRvVideoList;
    private ViewGroup mAdLayout;
    ListGSYVideoPlayer detailPlayer;
    private ArrayList<GSYVideoModel> mVideoList = new ArrayList();

    private int mId;
    VideoAlbumDetailAdapter mAdapter;
    private VideoInfo mInitVideoInfo;
    private DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    private RelativeLayout mParentAdLayout;

    private OrientationUtils orientationUtils;
    private boolean isPlay;
    private boolean isPause;

    public static void launch(Context context, VideoInfo info) {
        Intent intent = new Intent(context, VideoPlayerActivity.class);
        intent.putExtra(CommonConstant.VIDEO_DATA_KEY, info);
        intent.putExtra(CommonConstant.ALBUMS_ID, info.getAlbumId());
        intent.putExtra(CommonConstant.ALBUMS_IMAGE, info.getImage());
        context.startActivity(intent);
    }

    public static void launch(Context context, VideoCategoryList.CategoryBean.AlbumBean info) {
        Intent intent = new Intent(context, VideoPlayerActivity.class);
        intent.putExtra(CommonConstant.ALBUMS_ID, info.getId());
        intent.putExtra(CommonConstant.ALBUMS_IMAGE, info.getImageUrl());
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);

        ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(mDisplayMetrics);
        mParentAdLayout = new RelativeLayout(this);
        mParentAdLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mParentAdLayout.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        ((ViewGroup)getWindow().getDecorView()).addView(mParentAdLayout);

        detailPlayer = findViewById(R.id.detail_player);
        mRvVideoList = findViewById(R.id.related_video_list);
        mAdLayout = findViewById(R.id.ad_layout);
        mRvVideoList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mAdapter = new VideoAlbumDetailAdapter();
        mRvVideoList.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new MyOnItemClickListener());

        mInitVideoInfo = getIntent().getParcelableExtra(CommonConstant.VIDEO_DATA_KEY);
        mId = getIntent().getIntExtra(CommonConstant.ALBUMS_ID, 0);
        String imageUrl = getIntent().getStringExtra(CommonConstant.ALBUMS_IMAGE);
        if (mInitVideoInfo != null) {
            imageUrl = mInitVideoInfo.getImage();
        }


        // 停止musicService
        XApp.unbindMusicService();

        initVideoPlayer(imageUrl);

        loadData();
        addAd(mAdLayout);
    }

    private void initVideoPlayer(String imageUrl) {
        //普通模式
        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, detailPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);
        if (detailPlayer.getFullscreenButton() != null) {
            detailPlayer.getFullscreenButton().setOnClickListener(v -> {
                if (orientationUtils.getIsLand() != 1) {
                    //直接横屏
                    orientationUtils.resolveByClick();
                }
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detailPlayer.startWindowFullscreen(this, true, true);
            });
        }
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);

        //增加title
        detailPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        detailPlayer.getBackButton().setVisibility(View.VISIBLE);

        detailPlayer.setIsTouchWiget(true);
        //关闭自动旋转
        detailPlayer.setRotateViewAuto(false);
        detailPlayer.setLockLand(false);
        detailPlayer.setShowFullAnimation(false);
        detailPlayer.setNeedLockFull(true);
        detailPlayer.setRotateWithSystem(true);

        detailPlayer.setVideoAllCallBack(new MyVideoAllCallBack1());

        detailPlayer.setLockClickListener((view, lock) -> {
            if (orientationUtils != null) {
                //配合下方的onConfigurationChanged
                orientationUtils.setEnable(!lock);
            }
        });

        detailPlayer.getBackButton().setOnClickListener(v -> finish());

        if (!TextUtils.isEmpty(imageUrl)) {
            //增加封面
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            detailPlayer.setThumbImageView(imageView);
            Glide.with(this).load(imageUrl).fitCenter().into(imageView);
        }
    }

    private void loadData() {
        RetrofitService.getAlbumDetailList(mId, 0, 999)
            .compose(bindToLifecycle())
            .subscribe(new Observer<List<VideoInfo>>() {
                @Override
                public void onSubscribe(Disposable d) {
                }

                @Override
                public void onNext(List<VideoInfo> value) {
                    if (value != null && value.size() > 0) {
                        ArrayList<VideoInfo> videoList = new ArrayList<>();
                        videoList.addAll(value);
                        int index = 0;
                        for (VideoInfo info : value) {
                            mVideoList.add(new GSYVideoModel(info.getUrl(), info.getName()));
                            if (mInitVideoInfo != null && TextUtils.equals(mInitVideoInfo.getUrl(), info.getUrl())) {
                                index = videoList.indexOf(info);
                            }
                        }
                        mAdapter.addDatas(videoList);
                        mAdapter.notifyDataSetChanged();
                        detailPlayer.setUp(mVideoList, true, index);
                        detailPlayer.startPlayLogic();
                    }
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onComplete() {

                }
            });
    }

    private void addAd(ViewGroup parentView) {
        if (!XApp.showAD()) {
            parentView.setVisibility(View.GONE);
            return;
        }
        //人群属性
        AdSettings.setKey(new String[]{"baidu", "中国"});
        //创建广告 view
        String adPlaceID = XApp.getBannerID();//重 要 : 请 填 上 你 的 代 码 位 ID,否 则 无 法 请 求到广告
        AdView adView = new AdView(this, adPlaceID);
        //设置监听器
        adView.setListener(new AdViewListener() {
            @Override
            public void onAdReady(AdView adView) {
                Log.e("12345", "onAdReady");
            }

            @Override
            public void onAdShow(JSONObject jsonObject) {
                Log.e("12345", "onAdShow");
            }

            @Override
            public void onAdClick(JSONObject jsonObject) {
                Log.e("12345", "onAdClick");
            }

            @Override
            public void onAdFailed(String s) {
                Log.e("12345", "onAdFailed: " + s);
            }

            @Override
            public void onAdSwitch() {
                Log.e("12345", "onAdSwitch");
            }

            @Override
            public void onAdClose(JSONObject jsonObject) {
                Log.e("12345", "onAdClose");
            }
        });

        int width = Math.min(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels);
        int height = width * 3 / 20;
        //将 adView 添加到父控件中(注:该父控件不一定为您的根控件,只要该控件能通过 addView添加广告视图即可)
        RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(width, height);
        rllp.addRule(RelativeLayout.ALIGN_PARENT_TOP);

        parentView.addView(adView, rllp);
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onPause() {
        super.onPause();
        detailPlayer.getCurrentPlayer().onVideoPause();
        isPause = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (detailPlayer != null) {
            detailPlayer.getCurrentPlayer().onVideoResume();
        }
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isPlay && detailPlayer != null) {
            detailPlayer.getCurrentPlayer().release();
            isPlay = false;
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }

    class MyOnItemClickListener implements BaseRecyclerViewAdapter.OnItemClickListener<VideoInfo> {
        @Override
        public void onItemClick(int position, VideoInfo data) {
            detailPlayer.setUp(mVideoList, true, position);
            detailPlayer.startPlayLogic();
        }
    }

    class MyVideoAllCallBack1 extends MyVideoAllCallBack {
        @Override
        public void onPrepared(String url, Object... objects) {
            if (orientationUtils == null) {
                throw new NullPointerException("initVideo() or initVideoBuilderMode() first");
            }
            //开始播放了才能旋转和全屏
            // 是否启动旋转横屏，true表示启动
            orientationUtils.setEnable(true);
            isPlay = true;
        }

        @Override
        public void onAutoComplete(String url, Object... objects) {
            finish();
        }

        @Override
        public void onEnterFullscreen(String url, Object... objects) {
            // 添加全屏横幅广告
            mParentAdLayout.setVisibility(View.VISIBLE);
            if (mParentAdLayout.getChildCount() == 0) {
                addAd(mParentAdLayout);
            }
        }

        @Override
        public void onQuitFullscreen(String url, Object... objects) {
            if (orientationUtils != null) {
                orientationUtils.backToProtVideo();
            }
            // 隐藏全屏横幅广告
            mParentAdLayout.setVisibility(View.GONE);
        }
    }
}
